<template>
    <div class="address-edit">
        <van-cell-group>
            <van-field @input="validateData('contactName')" v-model="formData.contactName" :error-message="errorInfo.contactName" clearable label="收件人" placeholder="请填写收件人姓名" />
            <van-field @input="validateData('contactMobile')"  @blur="validateData('contactMobile')" v-model="formData.contactMobile" :error-message="errorInfo.contactMobile" clearable label="联系电话" placeholder="请填写收件人联系电话" />
            <van-field :value="areaText" :error-message="errorInfo.regionArea" readonly is-link clearable label="所在地区" placeholder="请选择所在地区" @click="handleShowAreaListShow" />
            <van-field @input="validateData('detailAddress')" type="textarea" :error-message="errorInfo.detailAddress" autosize v-model="formData.detailAddress" clearable label="详细地址" placeholder="请填写详细地址" />
        </van-cell-group>
        <van-cell-group style="margin-top:10px;">
            <van-switch-cell v-model="formData.isDefault" title="设为默认" />
        </van-cell-group>
        <van-row class="button-fixed-bottom" @click.native="handleSaveSubmit">
            <van-button bottom-action :loading="loading">
                <i>保存地址</i>
            </van-button>
        </van-row>
        <!--<van-popup v-model="areaListShowPopup" position="bottom">
            <van-area :area-list="areaList" @cancel="areaListShowPopup = false" :visible-item-count="4" @confirm="confirmArea" />
        </van-popup>-->
        <van-popup v-model="areaListShowPopup" position="bottom" :overlay="true" class="sites">
			<van-nav-bar title="所在地区" left-text="" left-arrow @click-left="hide_address_popup" @click-right="hide_address_popup">
				<van-icon name="close" slot="right" />
			</van-nav-bar>
			<div class="site_box">
				<div class="siteClass">
					<ul class="siteName">
						<li v-for="(value,index) in siteName" :class="index==0 ? 'on' : ''" :key='index' @click='siteClass($event,index)'>{{value}}</li>
					</ul>
				</div>
				<ul class="siteList">
					<li :class="index == 0 ? 'active' : ''" v-for='(value,index) in siteList' :key='index' @click.stop="getSite(value,index)">{{value.name}}
						<van-icon v-if='index==0' name="success" /> </li>
				</ul>
			</div>
		</van-popup>
		<van-toast :mask="true" class='addressLoading' message="加载中..." type="loading" v-model="getAddressLoading"></van-toast>
    </div>
</template>

<script>
import areaList from '@/common/js/area.js'
import { telRule } from '@/utils/validate.js'
import { getAddressInfo, saveAddressInfo, deleteAddressInfo } from '@/api/address/index.js'
import { getStoreArea, getProvince} from '@/api/goods/index.js'

export default {
    data () {
        return {
            loading: false,
            formData: {
                id: 0,
                contactName: '',
                contactMobile: '',
                regionArea: [],
                provinceCode: '',
                provinceName: '',
                cityCode: '',
                cityName: '',
                sectionCode: '',
                sectionName: '',
                streetCode: '',
                streetName: '',
                detailAddress: '',
                isDefault: false,
            },
            areaList,
            areaListShowPopup: false,
            errorInfo: {
                contactName: '',
                contactMobile: '',
                regionArea: '',
                detailAddress: '',
            },
            siteName: [],
			siteList: [],
			areaText: '',
			getAddressLoading: false
			
        }
    },
    computed: {
//      getAreaText() {
//      	console.log(this.siteName)
//          const arr = this.siteName.map(el => el)
//          
//          return arr.join(' ')
//      }
    },
    methods: {
        getData () {
            getAddressInfo(this.formData.id).then((rst) => {
                if (rst.status == 0) {
                    this.formData.contactName = rst.data.contactName
                    this.formData.contactMobile = rst.data.contactMobile
                    this.formData.provinceCode = rst.data.provinceCode
                    this.formData.provinceName = rst.data.provinceName
                    this.formData.cityCode = rst.data.cityCode
                    this.formData.cityName = rst.data.cityName
                    this.formData.sectionCode = rst.data.sectionCode
                    this.formData.sectionName = rst.data.sectionName
                    this.formData.streetCode = rst.data.streetCode
                    this.formData.streetName = rst.data.streetName
                    this.formData.detailAddress = rst.data.detailAddress
                    this.formData.isDefault = rst.data.isDefault == 1
                    this.areaText = this.formData.provinceName + this.formData.cityName + this.formData.sectionName + this.formData.streetName
                    this.siteName = [this.formData.provinceName,this.formData.cityName,this.formData.sectionName,this.formData.streetName]
                } else {
                    this.$toast(rst.message ? rst.message : '获取用户地址失败，请稍后再试')
                }
            }).catch(() => {
                this.$toast('获取用户地址失败，请稍后再试')
            })
        },
        
        getProvinceData() {
        	getProvince().then((res)=>{
        		this.getAddressLoading = false
        		this.siteList = res.data
        	}).catch(()=>{
        		this.$toast('获取默认省信息失败，请稍后再试')
        	})
        },
        
        validateData (type = '') {
            if (type == '' || type == 'contactName') {
                this.errorInfo.contactName = ''
                if (this.formData.contactName === '') {
                    this.errorInfo.contactName = '请填写收件人姓名'
                    return false
                }
            }
            if (type == '' || type == 'contactMobile') {
                this.errorInfo.contactMobile = ''
                if (this.formData.contactMobile === '') {
                    this.errorInfo.contactMobile = '请填写联系电话'
                    return false
                } else if (!telRule.test(this.formData.contactMobile)) {
                    this.errorInfo.contactMobile = '请填写正确的联系电话'
                    return false
                }
            }
            if (type == '' || type == 'regionArea') {
                this.errorInfo.regionArea = ''
                if (this.formData.regionArea === '') {
                    this.errorInfo.regionArea = '请选择所在地区'
                    return false
                }
            }
            if (type == '' || type == 'detailAddress') {
                this.errorInfo.detailAddress = ''
                if (this.formData.detailAddress === '') {
                    this.errorInfo.detailAddress = '请填写详细地址'
                    return false
                }
            }
            return true
        },
        handleSaveSubmit () {
            let isValid = this.validateData()
            if (!isValid) {
                return false
            }
            this.loading = true
            saveAddressInfo(
                this.formData.id,
                this.formData.contactName,
                this.formData.contactMobile,
                this.formData.provinceCode,
                this.formData.cityCode,
                this.formData.sectionCode,
                this.formData.streetCode,
                this.formData.detailAddress,
                this.formData.isDefault ? 1 : 0,
            ).then((rst) => {
                this.loading = false
                if (rst.status == 0) {
                    this.$toast(rst.message ? rst.message : '保存用户地址成功')
//                  this.$router.push({name:'addressList'})
                    this.$router.go(-1)
                } else {
                    this.$toast(rst.message ? rst.message : '保存用户地址失败，请稍后再试')
                }
            }).catch((msg) => {
                this.loading = false
                this.$toast('保存用户地址失败，请稍后再试')
            })
        },
		handleShowAreaListShow () {
			this.areaListShowPopup = true
			if(this.siteName.length == 0){
				this.siteName = ['浙江省','宁波市','鄞州区']
			}
		},
        hide_address_popup() {
			this.areaListShowPopup = false
			this.areaText = this.siteName.join('')
		},
		siteClass(el, index) {
			this.getAddressLoading = true
				el.currentTarget.parentNode.childNodes.forEach(function(val) {
					val.classList.remove('on');
				})
				el.currentTarget.classList.add("on");
				switch(index) {
					case 0:
						this.formData.cityCode = ''
						this.formData.sectionCode = ''
						this.formData.streetCode = ''
						
						
						for(let i in this.provinceList) {
							this.classify.push(this.provinceList[i]);
						}
						
						this.siteName[1] = ''
						this.siteName[2] = ''
						this.siteName[3] = ''
						
			
						this.getProvinceData()
						break;
					case 1:
						this.siteType = 1
						
						this.formData.sectionCode = ''
						this.formData.streetCode = ''
						
						this.siteName[2] = ''
						this.siteName[3] = ''
						
						this.getSiteListData()
						break;
					case 2:
						this.siteType = 2
						
						this.formData.streetCode = ''
						
						this.siteName[3] = ''
						this.getSiteListData();
						break;
					case 3:
						this.siteType = 3
						this.formData.sectionCode = ''
						this.formData.streetCode = ''
						
						this.getSiteListData()
						break;
					default:
						break;
				}
			},
			getSite(index, title) {
				this.getAddressLoading = true
				this.classify = [];
				
				var siteNameS = document.getElementsByClassName('siteName')[0].childNodes;
				
				siteNameS.forEach(function(data){
					data.classList.remove('on');
				});
				
				
				if(index.p_type == 0 ){
					this.siteType = 1
					this.siteName[1] = ''
					this.siteName[2] = ''
					this.siteName[3] = ''
					this.formData.provinceCode = index.code;
					this.formData.cityCode = ''
					this.formData.sectionCode = ''
					this.formData.streetCode = ''
					siteNameS[0].classList.add("on");
				}else if(index.p_type == 1){
					this.siteType = 2
					this.formData.provinceCode
					this.formData.cityCode = index.code;
					this.formData.sectionCode = ''
					this.formData.streetCode = ''
					
					this.siteName[2] = ''
					this.siteName[3] = ''
					
					this.siteName[1] = index.name
					
					siteNameS[1].classList.add("on");
				}else if(index.p_type == 2){
					this.siteType = 3
					this.formData.provinceCode
					this.formData.cityCode
					this.formData.sectionCode = index.code;
					this.formData.streetCode = ''
					this.siteName[3] = ''
//					this.siteName[4] = ''
					this.siteName[2] = index.name
					
					siteNameS[2].classList.add("on");
				}else if(index.p_type == undefined){
					this.siteName[3] = index.name
					this.formData.streetCode = index.code
					siteNameS[3].classList.add("on");
				}
				this.getSiteListData();
			},
			getSiteListData() {
				getStoreArea(this.siteType, this.formData.provinceCode, this.formData.cityCode, this.formData.sectionCode).then((res) => {
					this.getAddressLoading = false
					this.siteList = []
					for(let x in res.data) {
						this.siteList.push(res.data[x]);
					}
					if(res.data.length == 0){
						this.areaListShowPopup = false
					}
					this.areaText = this.siteName.join('')
				}).catch(() => {
					
					this.loading = false;
				})
			}
    },
    created () {
//      this.formData.id = this.$route.query.id ? this.$route.query.id : 0
//      if (this.formData.id != 0) {
//          this.getData()
//      } 
       this.getProvinceData()
    },
    activated () {
    	this.formData.id = this.$route.query.id ? this.$route.query.id : 0
        if (this.formData.id != 0) {
            this.getData()
        } else {
        	this.formData.contactName = ''
            this.formData.contactMobile = ''
            this.formData.provinceCode = ''
            this.formData.provinceName = ''
            this.formData.cityCode = ''
            this.formData.cityName = ''
            this.formData.sectionCode = ''
            this.formData.sectionName = ''
            this.formData.streetCode = ''
            this.formData.streetName = ''
            this.formData.detailAddress = ''
            this.areaText = ''
        }
	},
}
</script>

<style lang="scss">
@import "../../styles/color.scss";
.address-edit{
	.sites {
		top: 50%;
		.van-popup--bottom {
			top: initial;
		}
		.van-icon-success {
			color: $checkBoxColor;
			margin-left: 5px;
		}
		.van-tab {
			display: inline-block;
			padding: 0 15px;
		}
		.van-tabs__nav {
			display: inline-block;
		}
		.van-tabs__wrap {
			position: relative;
			top: 46px;
			width: 100%;
			text-align: left;
		}
		.van-tabs__content {
			position: absolute;
			top: 90px;
			line-height: 50px;
			padding: 0 15px;
		}
		li {
			line-height: 40px;
		}
		li.active {
			color: $checkBoxColor;
		}
		.site_box {
			padding-top: 46px;
			li.on {
				border-bottom: 2px solid $checkBoxColor;
				color: $checkBoxColor;
			}
		}
		.siteClass {
			ul {
				overflow: hidden;
				border-bottom: 1px solid #E5E5E5;
				li {
					float: left;
					width: 20%;
				}
			}
		}
		.siteList {
			text-align: left;
			padding-left: 15px;
		}
	}
	.addressLoading{
		z-index: 99999 !important;
		top: 83%;
		width: 90px;
		min-height: 90px;
		padding: 0;
	}
	.van-nav-bar .van-icon{
		font-weight: 400;
		color: #666666;
		font-size: 0.4rem;
	}
}
</style>
